# !/usr/bin/python
# -*- coding: utf-8 -*-

"""
@contact: 微信 1257309054
@file: mpl_plot.py
@time: 2022/5/23 15:05
@author: LDC
"""

import matplotlib
import numpy as np
import threading
import win32api, win32con

matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import mmap
import time
import datetime
from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes


# 运行计算
class my_Thread(threading.Thread):
    def __init__(self, adds, lineEdit_14):
        threading.Thread.__init__(self)
        self.adds = adds
        self.lineEdit_14 = lineEdit_14

    def run(self):
        self.traverse_data()

    def traverse_data(self):
        mmap_file = mmap.mmap(0, 1024, access=mmap.ACCESS_WRITE, tagname='share_mmap12')
        while 1:
            mmap_file.seek(0)
            str1 = mmap_file.read().translate(None, b'\x00').decode()
            if str1 != "":
                db_pkl = str1.split(',')
                if len(db_pkl) > 5:
                    data_0 = float(db_pkl[2])
                    data_1 = float(db_pkl[3])
                    data_2 = float(db_pkl[4])
                    data_3 = float(db_pkl[5])
                    self.adds.lineEdit.setText(str(data_0))
                    self.adds.lineEdit_2.setText(str(data_1))
                    self.adds.lineEdit_3.setText(str(data_2))
                    self.adds.lineEdit_4.setText(str(data_3))

            time.sleep(self.lineEdit_14)


# 画图
class drawPaint(threading.Thread):
    def __init__(self, selfs, adds, lineEdit_14):
        threading.Thread.__init__(self)
        self.adds = adds
        self.lineEdit_14 = lineEdit_14
        self.selfs = selfs

    def run(self):
        self.traverse_data(self.selfs, self.adds, self.lineEdit_14)

    def traverse_data(self, selfs, adds, lineEdit_14):
        mmap_file = mmap.mmap(0, 1024, access=mmap.ACCESS_WRITE, tagname='share_mmap12')
        while 1:
            start = time.time()
            # plt.clf()
            try:
                mmap_file.seek(0)
                str1 = mmap_file.read().translate(None, b'\x00').decode()
                if str1 != "":
                    db_pkl = str1.split(',')
                    selfs.x_data1.append(float(db_pkl[1]))
                    selfs.y_data1.append(float(db_pkl[2]))
                    selfs.x_data2.append(float(db_pkl[1]))
                    selfs.y_data2.append(float(db_pkl[3]))
                    selfs.x_data3.append(float(db_pkl[1]))
                    selfs.y_data3.append(float(db_pkl[4]))
                    selfs.x_data4.append(float(db_pkl[1]))
                    selfs.y_data4.append(float(db_pkl[5]))
                    comboBox_3Text = adds.comboBox_3.currentText()
                    comboBox_5Text = adds.comboBox_5.currentText()
                    comboBox_6Text = adds.comboBox_6.currentText()
                    comboBox_7Text = adds.comboBox_7.currentText()

                    Xmax1 = max(selfs.y_data1)
                    Xmax2 = max(selfs.y_data2)
                    Xmax3 = max(selfs.y_data3)
                    Xmax4 = max(selfs.y_data4)

                    list1 = []
                    list1.append(Xmax1)
                    if comboBox_3Text == comboBox_5Text:
                        list1.append(Xmax2)
                    if comboBox_3Text == comboBox_6Text:
                        list1.append(Xmax3)
                    if comboBox_3Text == comboBox_7Text:
                        list1.append(Xmax4)
                    selfs.drawingCurve(1, comboBox_3Text, selfs.x_data1, selfs.y_data1,
                                       max(list1))

                    list2 = []
                    list2.append(Xmax2)
                    if comboBox_5Text == comboBox_3Text:
                        list2.append(Xmax1)
                    if comboBox_5Text == comboBox_6Text:
                        list2.append(Xmax3)
                    if comboBox_5Text == comboBox_7Text:
                        list2.append(Xmax4)
                    selfs.drawingCurve(2, comboBox_5Text, selfs.x_data2, selfs.y_data2,
                                       max(list2)+20)

                    list3 = []
                    list3.append(Xmax3)
                    if comboBox_6Text == comboBox_3Text:
                        list3.append(Xmax1)
                    if comboBox_6Text == comboBox_5Text:
                        list3.append(Xmax2)
                    if comboBox_6Text == comboBox_7Text:
                        list3.append(Xmax4)

                    selfs.drawingCurve(3, comboBox_6Text, selfs.x_data3, selfs.y_data3,
                                       max(list3))

                    list4 = []
                    list4.append(Xmax4)
                    if comboBox_7Text == comboBox_3Text:
                        list4.append(Xmax1)
                    if comboBox_7Text == comboBox_5Text:
                        list4.append(Xmax2)
                    if comboBox_7Text == comboBox_6Text:
                        list4.append(Xmax3)
                    selfs.drawingCurve(4, comboBox_7Text, selfs.x_data4, selfs.y_data4,
                                       max(list4))
                    selfs.draw()
            except ValueError as e:
                print(e.mesg)
            end = time.time()
            # print('Running time: %s Seconds' % (end - start))
            time.sleep(lineEdit_14 - 0.005)


class Mplplot(FigureCanvas):
    def __init__(self, parent=None, width=5, height=3, dpi=100):
        # normalized for 中文显示和负号
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        plt.pause(0.01)
        self.x_data1 = []
        self.y_data1 = []
        self.x_data2 = []
        self.y_data2 = []
        self.x_data3 = []
        self.y_data3 = []
        self.x_data4 = []
        self.y_data4 = []
        self.host = None
        self.par1 = None
        self.par2 = None
        self.line1 = None
        self.line2 = None
        self.line3 = None
        self.line4 = None
        self.line1Show = True
        self.line2Show = True
        self.line3Show = True
        self.line4Show = True
        self.start_len = 0
        self.end_len = 0
        self.date_len = []
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        super(Mplplot, self).__init__(self.fig)
        self.setParent(parent)
        self.i = 0
        # FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        # FigureCanvas.updateGeometry(self)

    def add_line(self):

        self.host = HostAxes(self.fig, [0.05, 0.08, 0.86, 0.87])
        self.par1 = ParasiteAxes(self.host, sharex=self.host)
        self.par2 = ParasiteAxes(self.host, sharex=self.host)
        self.host.parasites.append(self.par1)
        self.host.parasites.append(self.par2)

        self.host.axis["right"].set_visible(False)

        self.par1.axis["right"].set_visible(True)
        self.par1.axis["right"].major_ticklabels.set_visible(True)
        self.par1.axis["right"].label.set_visible(True)

        self.par2.axis["right2"] = self.par2.new_fixed_axis(loc="right", offset=(40, 0))

        self.fig.add_axes(self.host)

        self.host.set_xlabel("采样时间")
        self.host.set_ylabel("y1", loc='top')
        self.par1.set_ylabel("y2", loc='bottom')
        self.par2.set_ylabel("y3", loc='bottom')

    # 绘制曲线l/+
    def drawingCurve(self, index, checkedText, x_data, y_data, maxValue):
        minYData = 0;
        if min(y_data) >0:
            pass
        else:
            minYData = min(y_data) - 10
        if index == 1:
            if self.line1Show and len(y_data) > 0 and len(y_data) == len(x_data):
                if checkedText == "y1":
                    if self.line1 is None:
                        self.line1, = self.host.plot([], [])
                        self.line1.set_color('#2196f3')
                    self.host.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.host.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y2":
                    if self.line1 is None:
                        self.line1, = self.par1.plot([], [])
                        self.line1.set_color('#2196f3')
                    self.par1.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par1.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y3":
                    if self.line1 is None:
                        self.line1, = self.par2.plot([], [])
                        self.line1.set_color('#2196f3')
                    self.par2.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par2.set_xlim([min(x_data), max(x_data) * 1.2])
                self.line1.set_xdata(x_data)
                self.line1.set_ydata(y_data)
                self.date_len.append(str(datetime.datetime.now()))
        elif index == 2:
            if self.line2Show and len(y_data) > 0 and len(y_data) == len(x_data):
                if checkedText == "y1":
                    if self.line2 is None:
                        self.line2, = self.host.plot([], [])
                        self.line2.set_color('#ff9800')
                    self.host.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.host.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y2":
                    if self.line2 is None:
                        self.line2, = self.par1.plot([], [])
                        self.line2.set_color('#ff9800')
                    self.par1.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par1.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y3":
                    if self.line2 is None:
                        self.line2, = self.par2.plot([], [])
                        self.line2.set_color('#ff9800')
                    self.par2.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par2.set_xlim([min(x_data), max(x_data) * 1.2])
                self.line2.set_xdata(x_data)
                self.line2.set_ydata(y_data)
        elif index == 3:
            if self.line3Show and len(y_data) > 0 and len(y_data) == len(x_data):
                if checkedText == "y1":
                    if self.line3 is None:
                        self.line3, = self.host.plot([], [])
                        self.line3.set_color('#ff5722')
                    self.host.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.host.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y2":
                    if self.line3 is None:
                        self.line3, = self.par1.plot([], [])
                        self.line3.set_color('#ff5722')
                    self.par1.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par1.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y3":
                    if self.line3 is None:
                        self.line3, = self.par2.plot([], [])
                        self.line3.set_color('#ff5722')
                    self.par2.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par2.set_xlim([min(x_data), max(x_data) * 1.2])
                self.line3.set_xdata(x_data)
                self.line3.set_ydata(y_data)
        elif index == 4:
            if self.line4Show and len(y_data) > 0 and len(y_data) == len(x_data):
                if checkedText == "y1":
                    if self.line4 is None:
                        self.line4, = self.host.plot([], [])
                        self.line4.set_color('#795548')
                    self.host.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.host.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y2":
                    if self.line4 is None:
                        self.line4, = self.par1.plot([], [])
                        self.line4.set_color('#795548')
                    self.par1.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par1.set_xlim([min(x_data), max(x_data) * 1.2])
                elif checkedText == "y3":
                    if self.line4 is None:
                        self.line4, = self.par2.plot([], [])
                        self.line4.set_color('#795548')
                    self.par2.set_ylim([minYData, maxValue + 10])
                    if len(y_data) > 1:
                        self.par2.set_xlim([min(x_data), max(x_data) * 1.2])
                self.line4.set_xdata(x_data)
                self.line4.set_ydata(y_data)

    # 下载Excal
    def downloadExcal(self, lens):
        strs = ""
        if lens == 0:
            now_time = datetime.datetime.now().strftime("%H%M%S")
            # 全部下载
            f = open("All" + str(now_time) + ".txt", 'w')
            lens = len(self.y_data1)
            for a in range(lens):
                strs = strs + str(self.date_len[a]) + "   " + str(self.y_data1[a]) + "   " + str(
                    self.y_data2[a]) + "   " + str(
                    self.y_data3[a]) + "   \n"
            f.write(strs)  # 将字符串写入文件中
            f.close()
            win32api.MessageBox(0, "数据下载成功，文件名:"+"All" + str(now_time)+".txt", "提示:", win32con.MB_OK)
        else:
            lens = len(self.y_data1)

            f = open('data_' + str(self.i) + '.txt', 'w')
            self.end_len = lens
            for a in range(lens):
                if a <= self.end_len and a >= self.start_len:
                    strs = strs + str(self.date_len[a]) + "   " + str(self.y_data1[a]) + "   " + str(
                        self.y_data2[a]) + "   " + str(
                        self.y_data3[a]) + "   \n"
            self.start_len = lens
            f.write(strs)  # 将字符串写入文件中
            f.close()
            win32api.MessageBox(0, "数据下载成功，文件名:" + 'data_' + str(self.i) + '.txt', "提示:", win32con.MB_OK)

    # 曲线显示隐藏控制
    def curveControl(self, index, judge):
        if index == 1:
            if judge:
                self.line1Show = True
                if len(self.y_data1) > 0:
                    self.line1.set_ydata(self.y_data1)
            else:
                if self.line1 is not None:
                    lists = np.array([0])
                    self.line1.set_ydata(lists)
                self.line1Show = False
        elif index == 2:
            if judge:
                self.line2Show = True
                if len(self.y_data2) > 0:
                    self.line1.set_ydata(self.y_data2)
            else:
                if self.line2 is not None:
                    lists = np.array([0])
                    self.line2.set_ydata(lists)
                self.line2Show = False
        elif index == 3:
            if judge:
                self.line3Show = True
                if len(self.y_data3) > 0:
                    self.line1.set_ydata(self.y_data3)
            else:
                if self.line3 is not None:
                    lists = np.array([0])
                    self.line3.set_ydata(lists)
                self.line3Show = False
        elif index == 4:
            if judge:
                self.line4Show = True
                if len(self.y_data4) > 0:
                    self.line1.set_ydata(self.y_data4)
            else:
                if self.line4 is not None:
                    lists = np.array([0])
                    self.line4.set_ydata(lists)
                self.line4Show = False

    def my_Thread(self, adds, lineEdit_14):
        my_Threads = my_Thread(adds, lineEdit_14)
        return my_Threads

    def drawPaint(self, adds, lineEdit_14):
        drawPaints = drawPaint(self, adds, lineEdit_14)
        return drawPaints

    def clearPage(self):
        if self.line1 is not None:
            lists = np.array([0])
            self.line1.set_ydata(lists)
            self.line2.set_ydata(lists)
            self.line3.set_ydata(lists)
            self.line4.set_ydata(lists)
            self.draw()
